#include <os/mm.h>

static ptr_t kernMemCurr = FREEMEM_KERNEL;
static ptr_t userMemCurr = FREEMEM_USER;
static int kernValid[16] = {0};
static int userValid[16] = {0};
ptr_t allocKernelPage(int numPage)
{
    // align PAGE_SIZE
    int num;
    for (num = 0; num < 16; num++)
    {
        if (kernValid[num] == 0)
        {
            kernValid[num] = 1;
            break;
        }
    }

    ptr_t ret = ROUND(FREEMEM_KERNEL + (num)*PAGE_SIZE, PAGE_SIZE);
    // kernMemCurr = ret + numPage * PAGE_SIZE;
    return ret;
}

ptr_t allocUserPage(int numPage)
{
    // align PAGE_SIZE
    int num;
    for (num = 0; num < 16; num++)
    {
        if (userValid[num] == 0)
        {
            userValid[num] = 1;
            break;
        }
    }
    ptr_t ret = ROUND(FREEMEM_USER + (num)*PAGE_SIZE, PAGE_SIZE);
    // ptr_t ret = ROUND(userMemCurr, PAGE_SIZE);
    // userMemCurr = ret + numPage * PAGE_SIZE;
    return ret;
}

void freeKernelPage(ptr_t address)
{
    int num = ((address - INIT_KERNEL_STACK) >> 12) - 1;
    kernValid[num] = 0;
}

void freeUserPage(ptr_t address)
{
    int num = ((address - INIT_USER_STACK) >> 12);
    userValid[num] = 0;
}
